package cn.com.lms.business.emprev.web;

import cn.com.lms.business.core.constant.BNZConstants;
import cn.com.lms.business.core.util.FastDfsUtils;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.course.service.FbCourseInfoService;
import cn.com.lms.business.emprev.persistence.entity.EmpRecordMaintenanceVo;
import cn.com.lms.business.emprev.service.EmpRecordMaintenanceVoService;
import cn.com.lms.business.excel.ExcelService;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import cn.com.lms.config.DfsResConfig;
import com.bnzj.cloud.business.core.persistence.entity.SysSetting;
import com.bnzj.cloud.business.core.service.SysSettingService;

import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.util.EntityUtils;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;

import com.bnzj.core.util.BeanUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @Author: 16266
 * @DateTime: 2020/3/18 14:45
 * @Description: 备案维护控制器
 */
@Tag(name = "导入备案维护", description = "导入员工信息更新备案维护")
@RestController
@RequestMapping(value = "/rec/mtc")
public class EmpRecordMaintenanceVoController {

    @Autowired
    private ExcelService excelService;

    @Autowired
    private EmpRecordMaintenanceVoService empRecordMaintenanceVoService;

    @Autowired
    private FastDfsUtils fastDfsUtils;

    @Operation(summary = "导入员工信息")
    @PostMapping(value = "/import")
    public ResponseResult<?> importExcel(@RequestParam("excelFile") MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        InputStream inputStream = null;
        StringBuilder sb = new StringBuilder();
        try {
            inputStream = multipartFile.getInputStream();
            List<Map<String, String>> maps = excelService.readExcel(filename, inputStream);
            int i = 1;
            for (Map<String, String> map : maps) {
                if (StringUtils.isEmpty(map.get("工号")) || StringUtils.isEmpty(map.get("是否备案"))) {
                    sb.append("第" + i + "行导入失败!");
                }
                i++;
                if (StringUtils.isNotBlank(map.get("工号")) && StringUtils.isNotBlank(map.get("是否备案"))) {
                    String account = map.get("工号");
                    EmpRecordMaintenanceVo empRecordMaintenanceVoDb = empRecordMaintenanceVoService.findByAccount(account);
                    if (ObjectUtils.isNotEmpty(empRecordMaintenanceVoDb)) {
                        EmpRecordMaintenanceVo empRecordMaintenanceVo = new EmpRecordMaintenanceVo();
                        empRecordMaintenanceVo.setIsRecord(map.get("是否备案"));
                        empRecordMaintenanceVo.setJobTypeName(map.get("岗位分类"));
                        BeanUtils.copyProperties(empRecordMaintenanceVo, empRecordMaintenanceVoDb);
                        empRecordMaintenanceVoService.save(empRecordMaintenanceVoDb);
                    } else {
                        sb.append("工号" + account + "不存在!");
                    }
                }
            }
        } catch (Exception e) {
            return ResponseResult.bizException(new BusinessException(e.getMessage(),
                    String.valueOf(ResultCode.FAILURE)));
        }
        if (!StringUtils.isEmpty(sb.toString())) {
            sb.append("请确认'工号','是否备案'已填。");
            return ResponseResult.bizException(new BusinessException(sb.toString(), String.valueOf(ResultCode.FAILURE)));
        }
        return ResponseResult.success();
    }

    @Autowired
    private DfsResConfig dfsResConfig;

    @Operation(summary = "下载excel模板")
    @PostMapping(value = "/download")
    public ResponseResult<?> downloadExcel(HttpServletResponse response, HttpServletRequest request) {
        String fileUrl = infoService.getSysSettingValue(BNZConstants.EXCEL_URL);
        if (StringUtils.isEmpty(fileUrl)) {
            return ResponseResult.failure(0, "");
        }
        try {
            byte[] data = fastDfsUtils.download(fileUrl);
            //String userAgent = request.getHeader("user-agent").toLowerCase();
            //火狐浏览器编码问题
//            if (userAgent.contains("firefox")) {
//                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");    // GBK
////                response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
////                response.setHeader("Content-Disposition", "attachment;filename=" + Base64.encodeBase64String(fileName.getBytes("UTF-8")));
//                response.setHeader("Content-Disposition", String.format("attachment;filename=\"%s\"", URLEncoder.encode(fileName, "ISO-8859-1")));
//            } else {
//                response.setHeader("Content-Type");
//                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("员工备案模板", "UTF-8"));
//            }
            response.setContentType("application/octet-stream");

            // 写出
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(data, outputStream);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.failure(ResultCode.FAILURE, "下载失败");
        }
    }

    @Autowired
    private FbCourseInfoService infoService;

    @Autowired
    private SysSettingService sysSettingService;

    @Operation(summary = "上传EXCEL模板URL保存到数据库")
    @PostMapping(value = "/upload")
    public ResponseResult<?> uploadExcel(@RequestParam("excelFile") MultipartFile multipartFile) {
        ResponseResult<String> stringResponseResult = fastDfsUtils.uploadFile(multipartFile);
        String url = stringResponseResult.getData();
        SysSetting sysSetting = new SysSetting();
        sysSetting.setKey(BNZConstants.EXCEL_URL);
        sysSetting.setValue(url);
        sysSetting.setDescription("员工备案-导入模板.xlsx");
        sysSetting.setName("员工备案-导入模板.xlsx");
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        EntityUtils.saveBefore(sysSetting, currentUser.getAccount(), currentUser.getCname());
        sysSettingService.save(sysSetting);
        return ResponseResult.success();
    }
}